<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>mongodb | 学习笔记</title><meta name="author" content="lzoxun"><meta name="copyright" content="lzoxun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="非关系型数据库-基于分布式文件存储的NoSQL  下载安装(M层)官网下载  MongoDB Community Server 社区版 MongoDB Enterprise Server 企业版  MongoDb Tools 安装 安装  选择 complete 完全安装非自定义,不要勾选 Install MongoDB Compass 安装完成之后可能要配置环境变量   开启数据库  终端输入">
<meta property="og:type" content="article">
<meta property="og:title" content="mongodb">
<meta property="og:url" content="http://example.com/2023/07/22/server/node/server-mongodb/index.html">
<meta property="og:site_name" content="学习笔记">
<meta property="og:description" content="非关系型数据库-基于分布式文件存储的NoSQL  下载安装(M层)官网下载  MongoDB Community Server 社区版 MongoDB Enterprise Server 企业版  MongoDb Tools 安装 安装  选择 complete 完全安装非自定义,不要勾选 Install MongoDB Compass 安装完成之后可能要配置环境变量   开启数据库  终端输入">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-07-22T07:14:09.687Z">
<meta property="article:modified_time" content="2023-07-22T07:14:09.687Z">
<meta property="article:author" content="lzoxun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2023/07/22/server/node/server-mongodb/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":true,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'mongodb',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-22 15:14:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="学习笔记"><span class="site-name">学习笔记</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">mongodb</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-22T07:14:09.687Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-22T07:14:09.687Z" title="更新于 2023-07-22 15:14:09">2023-07-22</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="mongodb"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>非关系型数据库-基于分布式文件存储的NoSQL</p>
</blockquote>
<h2 id="下载安装-M层"><a href="#下载安装-M层" class="headerlink" title="下载安装(M层)"></a>下载安装(M层)</h2><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download">官网下载</a></p>
<ul>
<li>MongoDB Community Server 社区版</li>
<li>MongoDB Enterprise Server 企业版</li>
</ul>
<p><a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/database-tools">MongoDb Tools</a></p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><ol>
<li><p>安装</p>
<ul>
<li>选择 complete 完全安装非自定义,不要勾选 Install MongoDB Compass</li>
<li>安装完成之后可能要配置环境变量</li>
</ul>
</li>
<li><p>开启数据库</p>
<ul>
<li>终端输入 mongod 执行(一般会提示缺少 C:&#x2F;data&#x2F;db 手动新建目录就行了)</li>
<li>或 mongod –dbpath d:&#x2F;data&#x2F;db 指定数据库路径<ul>
<li>可设置配置文件 <code>mongod.conf</code></li>
<li>通过 mongod -f mongod.conf</li>
</ul>
</li>
<li>执行成功后后面有一闪一闪的光标,数据库开启成功(窗口不用关闭)</li>
</ul>
</li>
<li><p>连接数据库</p>
<ul>
<li>开启新终端 输入 mongo</li>
<li>输入 show dbs 出现数据库说明连接成功了</li>
</ul>
</li>
<li><p>linux arch系列</p>
<ul>
<li>安装aur:mongodb、 mongodb-tools</li>
<li>创建并添加权限:chmod 777 &#x2F;data&#x2F;db</li>
</ul>
</li>
<li><p>centos 安装</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">配置源 vim /etc/yum.repos.d/mongodb-org-5.0.repo</span> </span><br><span class="line">[mongodb-org-5.0]</span><br><span class="line">name=MongoDB Repository</span><br><span class="line">baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/</span><br><span class="line">gpgcheck=1</span><br><span class="line">enabled=1</span><br><span class="line">gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"> yum install -y mongodb-org</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"> systemctl start mongod</span></span><br><span class="line"></span><br><span class="line">mongodb 数据默认存储目录为 /var/lib/mongo ,可以通过 cat /etc/mongodb.conf 查看或设置</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">重启或关闭可能造成，数据损坏，导致启动错误, 可以查看 /tmp/mongodb-27017.sock  ,有就删除</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">或 <span class="built_in">rm</span> -f //xxx//x/data/db/*.lock  ,修复  mongod --repair --dbpath=//xx/x/x/data/db</span></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li><p>源码安装</p>
</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">下载 解压</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建存储数据和日志的目录</span></span><br><span class="line">mkdir -p /mongod/data /mongod/log</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">进入mongodb加油目录 启动服务</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--fork 后台启动</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--auth 开启认证模式</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--logappend 追加方式记录日志</span></span><br><span class="line">mongod --port=27017 --dbpath=/mongod/data --logpath=/mongod/log/mongodb.log --bind_ip=0.0.0.0 --fork</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mongo控制台外关闭</span></span><br><span class="line">mongod --port=27017 --dbpath=/mongod/data --shutdown</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">控制台中关闭</span></span><br><span class="line">use admin</span><br><span class="line">db.shutdownServer()</span><br><span class="line">exit</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">指定配置文件/xx/xx/xx/mongod.conf</span></span><br><span class="line">mongod -f /xx/xx/xx/mongod.conf 启动</span><br></pre></td></tr></table></figure>

<h3 id="连接数据库"><a href="#连接数据库" class="headerlink" title="连接数据库"></a>连接数据库</h3><h4 id="图形工具连接"><a href="#图形工具连接" class="headerlink" title="图形工具连接"></a>图形工具连接</h4><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/compass">官方工具 compass</a><br><a target="_blank" rel="noopener" href="http://www.navicat.com.cn/what-is-navicat-for-mongodb">navicat</a><br><a target="_blank" rel="noopener" href="https://robomongo.org/">robo 3t</a><br><a target="_blank" rel="noopener" href="https://nosqlbooster.com/downloads">nosqlbooster</a></p>
<h4 id="工具连接远程"><a href="#工具连接远程" class="headerlink" title="工具连接远程"></a>工具连接远程</h4><blockquote>
<p>  不连接远程ssh 默认本地连接</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&quot;../../../static/img/mongodToolSSH.jpg&quot;</span> <span class="attr">alt</span>=<span class="string">&quot;ssh&quot;</span> <span class="attr">style</span>=<span class="string">&quot;zoom:50%;&quot;</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&quot;../../../static/img/2022-09-04_231517.jpg&quot;</span> <span class="attr">style</span>=<span class="string">&quot;zoom:50%;&quot;</span> /&gt;</span></span><br></pre></td></tr></table></figure>

<p>默认无密码登陆，如果设置了 –auth 就要选择密码连接</p>
<h4 id="命令行连接"><a href="#命令行连接" class="headerlink" title="命令行连接"></a>命令行连接</h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo mongodb://mongoroot:mongopwd@114.115.xxx.xxx</span><br></pre></td></tr></table></figure>

<h4 id="mongoose-连接"><a href="#mongoose-连接" class="headerlink" title="mongoose 连接"></a>mongoose 连接</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">&quot;mongodb://localhost/pro-node-lagou&quot;</span>, &#123;&#125;)</span><br><span class="line"><span class="comment">// 远程连接服务端，ip 设置0.0.0.0</span></span><br><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">&#x27;mongodb://mongoroot:xxxxxx@xxx.xxx.xxx.xxx:27017/pro-node-lagou?authSource=admin&#x27;</span>, &#123;&#125;)</span><br></pre></td></tr></table></figure>


<h2 id="安全"><a href="#安全" class="headerlink" title="安全"></a>安全</h2><h3 id="用户管理权限"><a href="#用户管理权限" class="headerlink" title="用户管理权限"></a>用户管理权限</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">mongo 的权限认证与登录，默认是不需要的，通过 --auth 开启的mongo服务，才需要</span><br><span class="line"><span class="meta prompt_">	</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">查看角色列表</span></span><br><span class="line">show roles</span><br><span class="line">root  # 超级账号，超级权限，只在admin库中可用</span><br><span class="line">dbOwner # 允许用户在指定数据库中执行任意操作</span><br><span class="line">read  #允许用户读取指定数据库</span><br><span class="line">readWrite # 允许用户读写指定数据库</span><br><span class="line">...</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建管理员账户，哪个创建的用户，默认归属那个数据库，只能操作那个数据库</span></span><br><span class="line">1、进入 use admin 管理员库设置管理员账号(默认没密码的)</span><br><span class="line">2、db.createUser(&#123;user:&quot;mongoroot&quot;,pwd:&quot;123456&quot;,roles:[&quot;root&quot;]&#125;)</span><br><span class="line">3、db.createUser(&#123;user:&quot;u1&quot;,pwd:&quot;123456&quot;,roles:[&#123; role: &quot;userAdminAnyDatabase&quot;, db: &quot;admin&quot; &#125;]&#125;) # 给u1指定库</span><br><span class="line">4、db.auth(&#x27;mongoroot&#x27;,&#x27;123456&#x27;) # 验证账号是否可用，1 成功</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">查看用户信息</span> </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="string">&quot;db&quot;</span> : <span class="string">&quot;testuser&quot;</span> 表示用户只能操作 testuser 数据库</span> </span><br><span class="line">show users</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">普通数据库下创建用户，u2只能操作这一个数据库</span></span><br><span class="line">db.createUser(&#123;user:&quot;u2&quot;,pwd:&quot;123456&quot;,roles:[&quot;dbOwner&quot;]&#125;)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">删除用户</span></span><br><span class="line">db.dropUser(&quot;u2&quot;)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">普通方式启动还是不需要账号密码就能登录，要以授权方式启动 --auth</span></span><br><span class="line">mongod --port=27017 --dbpath=/mongod/data --logpath=/mongod/log/mongodb.log --bind_ip=0.0.0.0 --fork --auth</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">配置文件添加 auth</span></span><br><span class="line">security:                                                                                                   	authorization: enabled</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">以账号登录,</span></span><br><span class="line">mongo -umongoroot -p123456 --authenticationDatabase=admin</span><br><span class="line">mongo -uu2 -p123456 --authenticationDatabase=testuser</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">普通连接，授权放方式登录</span></span><br><span class="line">mongo</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">use 到某个数据库<span class="built_in">test</span></span></span><br><span class="line">db.auth(&#x27;testRoleRser&#x27;,&#x27;123456&#x27;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="副本集-replication-复制"><a href="#副本集-replication-复制" class="headerlink" title="副本集(replication) 复制"></a>副本集(replication) 复制</h3><ol>
<li>一个活跃节点( <strong>Primary</strong> ) + N 个备份节点( <strong>Secondary</strong> )<ol>
<li>数据同步备份<ol>
<li>备份节点<code>定期，轮询</code>获取<code>主节点</code>的<code>数据库操作</code>，自己数据库副本<code>执行这些操作</code>，来<code>实现数据同步</code></li>
</ol>
</li>
<li>若活跃接点奔溃，数据库会将其中一个北方接点审计为活跃接点</li>
<li>备份节点不能主动去操作，想看的话先执行<code>rs.slaveOk()</code></li>
</ol>
</li>
<li>实现故障转移，主从复制<ol>
<li>解决问题 数据冗余备份，架构高可用</li>
<li>无法解决单节点压力问题( 硬件限制，并发访问压力)</li>
</ol>
</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">启动三个服务器，并设置所属的副本集 为 rs0</span></span><br><span class="line">mongod --port 27017 --dbpath &quot;D:/mongod/data1&quot; --replSet rs0</span><br><span class="line">mongod --port 27018 --dbpath &quot;D:/mongod/data2&quot; --replSet rs0</span><br><span class="line">mongod --port 27019 --dbpath &quot;D:/mongod/data3&quot; --replSet rs0</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">登录任意一个端口的 mongo，设置，初始化副本集</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">设置配置对象</span></span><br><span class="line">replSet_config = &#123;</span><br><span class="line">	_id:&quot;rs0&quot;,</span><br><span class="line">	members:[</span><br><span class="line">		&#123;</span><br><span class="line">			_id:0,</span><br><span class="line">			host:&quot;127.0.0.1:27017&quot;,</span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			_id:1,</span><br><span class="line">			host:&quot;127.0.0.1:27018&quot;,</span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			_id:2,</span><br><span class="line">			host:&quot;127.0.0.1:27019&quot;,</span><br><span class="line">		&#125;,</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">replSet_config = &#123;</span><br><span class="line">	_id:&quot;rs1&quot;,</span><br><span class="line">	members:[</span><br><span class="line">		&#123;</span><br><span class="line">			_id:1,</span><br><span class="line">			host:&quot;114.115.212.129:27018&quot;,</span><br><span class="line">		&#125;</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">初始化</span></span><br><span class="line">rs.initiate(replSet_config)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">查看副本集状态</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">health:1 健康的， stateStr:<span class="string">&quot;PRIMARY&quot;</span> 主节点</span></span><br><span class="line">rs.status()</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">验证数据同步备份</span></span><br><span class="line">rs.slaveOk() # 备份节点中执行后才能正常访问</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">登录指定端口</span></span><br><span class="line">mongo 127.0.0.1:27019 </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="多服务器副本集"><a href="#多服务器副本集" class="headerlink" title="多服务器副本集"></a>多服务器副本集</h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">服务器1</span> </span><br><span class="line">mkdir -p ./mongodb/repl/rs_1/log</span><br><span class="line">mkdir -p ./mongodb/repl/rs_1/data/db</span><br><span class="line"></span><br><span class="line">vim ./mongodb/repl/rs_1/mongod.conf # 填写 /etc/mongod.conf 内容 更改数据和日志地址 放开 replSetName: 副本集名称</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">服务器2</span> </span><br><span class="line">。。。</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">进入希望作为获得节点的服务器 mongo localhost:27018 启动数据库</span> </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">启动</span></span><br><span class="line">mongod -f /root/mongodb/repl/rs_1/mongod.conf</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">初始化 (可以直接传入配置)</span></span><br><span class="line">rs.initiate() </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">查看状态，rs.conf() 本质是 <span class="built_in">local</span> 库下 db.system.replset.find()</span></span><br><span class="line">config = rs.conf()</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">host不是ip需要修改</span></span><br><span class="line">config.members[0].host = &quot;192.168.16.134:27018&quot;</span><br><span class="line">rs.reconfig(config) # 重载配置</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">添加副本节点</span> </span><br><span class="line">rs.add(&quot;114.115.212.129:27018&quot;) # 云端端安全组开放端口，本地主要防火墙开放端口 ,  问题可能没关闭selinux</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">https://ke.qq.com/course/2930572/9864689478317964<span class="comment">#term_id=103043162 add无法添加 卡住</span></span></span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">程序连接方式 mongodb://username:password@192.168.56.101:27017,192.168.56.102:27017,192.168.56.103:27017/db_name?replicaSet=rschunqiu</span></span><br><span class="line"></span><br><span class="line">var config=&#123;_id:&quot;rs1&quot;,members:[&#123;_id:1,host:&quot;114.115.212.129:27018&quot;&#125;]&#125;</span><br></pre></td></tr></table></figure>




<h2 id="MongoDB-使用"><a href="#MongoDB-使用" class="headerlink" title="MongoDB 使用"></a>MongoDB 使用</h2><h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><ul>
<li><p>NoSQL <strong>( Not Only SQL )</strong> 非关系型数据库，是 不<code>同于传统关系型数据库</code> 的统称</p>
<ul>
<li>关系，表和表之间通过<strong>主键</strong>和<strong>外键</strong>是有联系的</li>
<li>一个主表，相关的东西，因为<strong>类型属性不同</strong>，需要存储到<strong>其他表</strong>中，用的时候，通过<strong>主外键取来</strong>使用</li>
<li>非关系型就不需要，相关的东西直接存放到文档，子属性中就行，<code>容易设计,且速度快</code></li>
</ul>
</li>
<li><p>对比关系数据库</p>
<ul>
<li>数据库(database) -&gt; 集合(collectiion) -&gt; 文档(document) -&gt; 字段(field)   -&gt; 索引(index)  -&gt; _id     -&gt;  视图(view) -&gt; 聚合操作</li>
<li>数据库(databsse) -&gt; 表(table) -&gt;         行(row) -&gt;        列(column) -&gt;    索引(index) -&gt;  主键  -&gt;  视图(view) -&gt; 表链接</li>
</ul>
</li>
<li><p>适用场景</p>
<ul>
<li>基于灵活的json文档模型，适合业务变化快，敏捷的快速开发</li>
<li>读写速度快，更适合处理大 数据</li>
</ul>
</li>
<li><p>NoSQL 的优点&#x2F;缺点</p>
<ul>
<li>分布式计算 : 当数据多了，快存不下了 ，添加扩展一个节点就可以继续存放了 </li>
<li>…</li>
</ul>
</li>
<li><p>默认数据库</p>
<ul>
<li><strong>admin</strong> : 管理员权限数据库</li>
<li><strong>local</strong> ：这个数据库永远不会被复制，可以用来储存本地服务器的任意集合</li>
<li><strong>config</strong>：保存分片相关信息</li>
</ul>
</li>
<li></li>
</ul>
<h3 id="操作指令"><a href="#操作指令" class="headerlink" title="操作指令"></a>操作指令</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mongodb  #数据库名</span><br><span class="line">mongod  #启动数据库</span><br><span class="line">mongo  #连接数据库</span><br><span class="line">mongoose #node操作数据库的指令</span><br></pre></td></tr></table></figure>

<h3 id="数据库增删改查"><a href="#数据库增删改查" class="headerlink" title="数据库增删改查"></a>数据库增删改查</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">数据库操作  ( DDL-database )</span></span><br><span class="line">show dbs; | show databases                 #查看全部不为空的数据库</span><br><span class="line">db.getMongo()                              #查看db链接机器地址</span><br><span class="line">db.dropDatabase()                          #删除数据库</span><br><span class="line">use &lt;db name&gt;;             #切换数据库(或创建数据库)</span><br><span class="line">db;或者db.getName();        #查看当前所在数据库</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">切换到数据库后，当前数据库集合操作 ( DDL-table )</span></span><br><span class="line">db.createCollection(&quot;testuser&quot;) # 创建集合，新集合没数据可能不会显示（灵活 不用知道字段以及类型）</span><br><span class="line">show collections | show tables;          #显示当前数据库中的集合（类似关系数据库中的表）</span><br><span class="line">db.testuser.drop()       #删除名为testuser的集合</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">文档操作 ( DML-table )</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">直接使用js语句操作</span></span><br><span class="line">for(var i=0;i&lt;10;i++)&#123;db.testusers.insert(&#123;name:`Name$&#123;i&#125;`,age:10+i&#125;)&#125;</span><br><span class="line"></span><br><span class="line">db.testuser.insert|save([&#123;a:1,b:2&#125;])       # 插入多个文档，不写中开括号就插入单个，save(废弃)</span><br><span class="line">	-	直接往不存在的集合插入文档，默认会自动创建这个集合</span><br><span class="line">db.testuser.insertMany([&#123;a:1,b:2&#125;])        # 也是批量插入</span><br><span class="line">db.testuser.remove(&#123;&#125;)                     # 删除所有</span><br><span class="line">db.testuser.remove(&#123;a:1&#125;)                  # 删除 a=1的文档</span><br><span class="line"></span><br><span class="line">db.testuser.update(&#123;a:1&#125;,&#123;b:5&#125;)            # 替换原有文档成 &#123;b:5&#125; 只有_id 会保留</span><br><span class="line">    db.testuser.update(&#123;a:1&#125;,&#123;$set:&#123;b:5&#125;&#125;)     # 原有文档的基础上，修改或增加属性 (匹配到的1条)</span><br><span class="line">    db.testuser.update(&#123;a:1&#125;,&#123;$set:&#123;b:5&#125;&#125;,&#123;multi:true&#125;)     # 原有文档的基础上，修改或增加属性 (所有匹配到的)</span><br><span class="line">        -	参数 query,更新对象，不存在记录是否插入0|1，是否更新所有匹配（0|1 简写）</span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$inc:&#123;b:NumberInt(1)&#125;&#125;) # 找到a=1的文档，让它的b属性自增1</span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$unset:&#123;age:1&#125;&#125;) # 删除指定的 key,值随意</span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$push:&#123;list:&quot;ele&quot;&#125;&#125;) # 所有匹配记录，list (必须不存在的或是数组类型)字段push一个元素</span><br><span class="line">    db.testuser.updateMany(&#123;name:&quot;Name9&quot;&#125;,&#123;$push:&#123;&quot;list&quot;:&#123;$each:[&quot;up3&quot;,&quot;up4&quot;]&#125;&#125;&#125;) # 添加多个 $pushAll 不能用</span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$addToSet:&#123;list:&quot;no repeat ele&quot;&#125;) # 如果值存在，不添加，不存在才添加</span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$pop:&#123;list:1&#125;&#125;,0,1) #1 从后面删除，-1 从前面删除 </span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$pull:&#123;list:&quot;ele&quot;&#125;&#125;,0,1) # 通过值删除 </span><br><span class="line">    db.testuser.update(&#123;a:0&#125;,&#123;$pullAll:&#123;list:[&quot;ele1&quot;,&quot;ele2&quot;]&#125;&#125;,0,1) # 删除多个 </span><br><span class="line">    # $pop 删除</span><br><span class="line">    </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">查询 ( DQL-table )</span></span><br><span class="line">db.testuser.find()       # 查询当前所在数据库，testuser 集合里面的列表文档内容</span><br><span class="line">	db.testuser.find(&#123;age:20&#125;) # 查询年龄为20的文档</span><br><span class="line">	db.testuser.find(&#123;age:20,name:1&#125;) # 查询年龄为20,并且name为1的文档</span><br><span class="line">	db.testuser.find(&#123;age:&#123;$ne:20&#125;&#125;) # 查询年龄不为20的文档</span><br><span class="line">	db.testuser.find(&#123;age:&#123;$gt:20&#125;&#125;) #查找age大于2的：$gte 大于等于、 $lt 小于 、$lte 小于等于</span><br><span class="line">    db.testuser.find(&#123;age:&#123;$gt:20,$lt:30&#125;&#125;) #20到30之间</span><br><span class="line">    db.testuser.find(&#123;$or:[&#123;age:1&#125;,&#123;name:2&#125;]&#125;) #或查询</span><br><span class="line">    db.testuser.find(&#123;age:20,&#123;$or:[&#123;sex:1&#125;,&#123;name:2&#125;]&#125;&#125;) # 查找年龄20并且sex为1，或 年龄20并且name为2的文档</span><br><span class="line">    db.testuser.find(&#123;age:&#123;$type:&quot;string&quot;&#125;&#125;) # 查询age类型为字符串的文档</span><br><span class="line">    db.testuser.find(&#123;name:&#123;$all:[&quot;Name0&quot;]&#125;&#125;) # 找出全部 name 为 Name0 的文档</span><br><span class="line">    db.testuser.find(&#123;list:&#123;$all:[&quot;test1&quot;,&quot;test2&quot;]&#125;&#125;) # 找出 list 中同时存在 test1 和 test2 的所有文档</span><br><span class="line">    db.testuser.find(&#123;list:&#123;$in:[&quot;test1&quot;,&quot;test2&quot;]&#125;&#125;) # 找出 list 中存在 test1 或 test2 的所有文档</span><br><span class="line">    db.testuser.find(&#123;list:&#123;$nin:[&quot;test1&quot;,&quot;test2&quot;]&#125;&#125;) # 找出 list 中不存在 test1 和 test2 的所有文档</span><br><span class="line">    db.testuser.find(&#123;name:/^1/&#125;) #正则查询</span><br><span class="line">     # 其他查询关键词 $lte 小于等于，$gte 大于等于 </span><br><span class="line">     </span><br><span class="line"></span><br><span class="line">    # 对找到的内容进行二次操作</span><br><span class="line">    db.testuser.find(&#123;条件&#125;,&#123;name:0,age:0&#125;) #0表示不要，1表示要，只能全部0（选择排除哪些字段）或全部1（选择哪些 ）</span><br><span class="line"></span><br><span class="line">    db.testuser.find(xxx).sort(&#123;age:1&#125;) #1升序、-1降序</span><br><span class="line">    db.testuser.find(xxx).limit(3) #取指定数目</span><br><span class="line">    db.testuser.find(xxx).skep(n).limit(3) #跳过n条再取指定数目 sort&gt;skep&gt;limit与书写顺序无关</span><br><span class="line">    db.testuser.find(xxx).count() #统计数目</span><br><span class="line"></span><br><span class="line">    db.testuser.findOne(xxx) #只取一条</span><br><span class="line">    db.testuser.distinct(&quot;name&quot;)       #查询名称不重复的记录</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">方法</span></span><br><span class="line"> .find().pretty()  # 容易阅读的格式返回 </span><br><span class="line"> .find().explain() # 查询分析</span><br><span class="line"> </span><br><span class="line"> var sfind = db.testusers.find();</span><br><span class="line"> sfind.next() # 查找下一个文档 .hasNext() 查看是否存在下一个文档</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">索引操作 提高查询效率</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建</span></span><br><span class="line">db.testuser.createIndex(&#123;key:1&#125;) # 单字段创建，key 创建索引的字段，1 按升序建，-1 按降序建</span><br><span class="line">db.testuser.createIndex(&#123;key:1,name:1&#125;) # 创建复合索引（索引一般给查询语句关联的字段建立）</span><br><span class="line">db.testuser.createIndex(&#123;age:1,xxx:xxxx&#125;,&#123;</span><br><span class="line">	background:true, # 是否后台创建</span><br><span class="line">	unique:true, # 是否设置唯一索引，索引字段不可重复，有重复值的字段也不能是唯一索引</span><br><span class="line">	name:&#x27;xx&#x27; # 所有名称</span><br><span class="line">&#125;) # 创建索引 ,多个就是复核索引</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">查询</span></span><br><span class="line">db.testuser.getIndexes() # 获取查看索引 _id 是默认的 </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">删除</span></span><br><span class="line">db.testuser.dropIndex(&#123;age:1&#125;) # 删除_id之外的索引</span><br><span class="line">db.testuser.dropIndexes() # 删除_id之外的所有索引</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">使用</span></span><br><span class="line">db.xxx.find(xx).explain()</span><br><span class="line"></span><br><span class="line">&quot;inputStage&quot; : &#123;</span><br><span class="line">    &quot;stage&quot; : &quot;IXSCAN&quot;, # 值为 IXSCAN 表示基于索引扫描，如果 COLLSCAN 全局扫描</span><br><span class="line">    &quot;keyPattern&quot; : &#123; # 使用了这些索引</span><br><span class="line">        &quot;age&quot; : 1</span><br><span class="line">    &#125;,</span><br><span class="line">    &quot;indexName&quot; : &quot;age_1&quot;, # 索引名称  </span><br><span class="line">    &quot;isUnique&quot; : true, # 是否是唯一索引</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="分组-group"><a href="#分组-group" class="headerlink" title="分组(group)"></a>分组(group)</h3><blockquote>
<p>  只能对本地单台机器数据处理</p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">分组统计</span> </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">统计各组身高不高于170的人数</span></span><br><span class="line">db.testuser.group(&#123;</span><br><span class="line">	key:&#123;sex:1&#125;,  # 分组字段，指定根据什么来分组 -- 如果通过性别 可分为两组 </span><br><span class="line">	cond:&#123;height:&#123;$lt:170&#125;,	# 查询条件  --   通过条件筛选，只对符合条件的进行操作</span><br><span class="line">	initial:&#123;counter=0&#125;,	# 初始化 -- 这边这样每组调用 reduce前 都会把counter从0开始</span><br><span class="line"><span class="meta prompt_">	# </span><span class="language-bash">聚合函数， 每组都会调用 reduce,参数一 是该组的每一个文档 ，result 全局属性</span></span><br><span class="line">	reduce:function(item,result)&#123;result.counter +=1 &#125;, </span><br><span class="line">	finalize:function(result)&#123;&#125; # 每统计一组后的回调函数，比如平均值就需要 reduce 相加完，来这里操作</span><br><span class="line">&#125;)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">通过分支最终的到的结果中留下 [&#123;sex:m, counter:10&#125;,&#123;sex:g, counter:20&#125;]</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">group 不支持分布式运算</span></span><br></pre></td></tr></table></figure>

<h3 id="聚合-aggragate"><a href="#聚合-aggragate" class="headerlink" title="聚合(aggragate)"></a>聚合(aggragate)</h3><blockquote>
<p>  主要对集合中的数据进行各种统计，并返回统计后的数据结果</p>
</blockquote>
<ol>
<li>常用管道操作<ol>
<li>$group : 将集合的统计结果进行分组</li>
<li>$match : 用于过滤数据，找出符合条件的文档 ( 类似 where 子句)</li>
<li>$project : 修改输入文档的结构，增加删除字段等</li>
<li>$limit : 限制管道返回的文档数量</li>
<li>$skip : 跳过指定属性的文档</li>
<li>$sort : 将文档排序后输出</li>
<li>$unwind : 将文档中某一个数组字段，拆分成多条，每条包含数组的一个值</li>
</ol>
</li>
<li>常用管道表达式<ol>
<li>平均数($avg)</li>
<li>求和($sum)</li>
<li>第一个($first)</li>
<li>最后一个($last)</li>
<li>最大&#x2F;小($max&#x2F;$min)</li>
<li>得到的数据放到数组中($push)</li>
</ol>
</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">数据通过多个管道进行处理</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">db.testuser.aggragate([&#123;操作1&#125;,&#123;操作2:&#123;xxx&#125;&#125;])</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">通过 sex 字段分组，得到每组的平均 height，保存到 avgerxxx 中</span></span><br><span class="line">db.testuser.aggragate([&#123;$group:&#123;_id:&quot;$sex&quot;,avgerxxx:&#123;$avg:&quot;$height&quot;&#125;&#125;&#125;])</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">通过 sex 字段分组，得到每组的最矮的人的高</span></span><br><span class="line">db.testuser.aggragate([&#123;$group:&#123;_id:&quot;$sex&quot;,minval:&#123;$min:&quot;$height&quot;&#125;&#125;&#125;])</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">把各组没人身高放到储存起来</span></span><br><span class="line">db.study.aggregate([&#123;$group:&#123;_id:&quot;$sex&quot;,heiarr:&#123;$push:&quot;$height&quot;&#125;&#125;&#125;])</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">多管道</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">身高大于180，男女生的数量</span></span><br><span class="line">db.study.aggregate([</span><br><span class="line">	&#123;$match:&#123;height:&#123;$gt:180&#125;&#125;&#125;,</span><br><span class="line">	&#123;$group:&#123;_id:&quot;$sex&quot;,sums:&#123;$sum:1&#125;&#125;&#125;</span><br><span class="line">])</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">身高大于180，男女生的数量，只输出属性</span></span><br><span class="line"> db.study.aggregate([</span><br><span class="line"> 	&#123;$match:&#123;height:&#123;$gt:170&#125;&#125;&#125;,</span><br><span class="line"> 	&#123;$group:&#123;_id:&quot;$sex&quot;,sums:&#123;$sum:1&#125;&#125;&#125;,</span><br><span class="line"> 	&#123;$project:&#123;_id:0,sums:1&#125;&#125;</span><br><span class="line"> ])</span><br><span class="line"><span class="meta prompt_"> </span></span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">身高大于180，男女生的数量,排序输出 -1 降序</span></span><br><span class="line">  db.study.aggregate([</span><br><span class="line"> 	&#123;$match:&#123;height:&#123;$gt:170&#125;&#125;&#125;,</span><br><span class="line"> 	&#123;$group:&#123;_id:&quot;$sex&quot;,sums:&#123;$sum:1&#125;&#125;&#125;,</span><br><span class="line"> 	&#123;$sort:&#123;sums:-1&#125;&#125; </span><br><span class="line"> ])</span><br><span class="line"><span class="meta prompt_"> </span></span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">找出女生，降序后，第2-3个，的名字与高度</span></span><br><span class="line"> db.study.aggregate([</span><br><span class="line"> 	&#123;$match:&#123;sex:&quot;g&quot;&#125;&#125;,</span><br><span class="line"> 	&#123;$sort:&#123;height:-1&#125;&#125;,</span><br><span class="line"> 	&#123;$skip:1&#125;,</span><br><span class="line"> 	&#123;$limit:2&#125;,</span><br><span class="line"> 	&#123;$project:&#123;_id:0,name:1,height:1&#125;&#125;</span><br><span class="line"> ])</span><br><span class="line"><span class="meta prompt_"> </span></span><br><span class="line"><span class="meta prompt_"> # </span><span class="language-bash">将文档数组类型字段 list，将文档拆分多个文档，每个文档的list 是原来 list数组的一个值</span></span><br><span class="line"> db.study.aggregate([&#123;$unwind:&quot;$list&quot;&#125;])</span><br></pre></td></tr></table></figure>

<h3 id="MapReduce"><a href="#MapReduce" class="headerlink" title="MapReduce"></a>MapReduce</h3><blockquote>
<p>  大数据计算模型，支持分布式，支持大量服务器同时工作 </p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">通过 map (第一个函数)，处理每一个文档，map函数中最后通过调用 emit(key,value) 返回键值对</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">系统会将emit的数据整理成 &lt;k1,[v1,v2,v5]&gt;  &lt;k2,[v3,v4]&gt; 这样的格式</span> </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">通过 reduce (第二个函数)，&lt;k1,[v1,v2,v5]&gt; 对每一个相同键进行处理  =&gt; 参数1 = k1,参数2 = [v1,v2,v5]</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">参数三，一个对象，把reduce输出的值进行各种处理</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">统计 study 集合中，相同年龄的有谁，输出到当前数据库的 res 集合中</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">res集合中 _id 就是 age的值，value就是age值，对应的学生名字</span></span><br><span class="line">var map = function()&#123;</span><br><span class="line"><span class="meta prompt_">	# </span><span class="language-bash">先把文档数据经过各种处理</span></span><br><span class="line">	emit(this.age,this.name); # 可以调用多次</span><br><span class="line">&#125;</span><br><span class="line">var reduce = function(age,values)&#123; # k1,[v1,v2,v5]</span><br><span class="line">	 return values</span><br><span class="line">&#125;</span><br><span class="line">db.study.mapReduce(map,reduce,&#123;out:&quot;res&quot;&#125;)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">optin</span>    </span><br><span class="line">	out 输出的集合名称</span><br><span class="line">	query 塞选完再执行map</span><br><span class="line">	sort 排序完再执行map</span><br><span class="line">	limit 限制个数执行map</span><br><span class="line">	</span><br><span class="line">db.study.mapReduce(map,reduce,&#123;</span><br><span class="line">	out:&quot;res&quot;,</span><br><span class="line">	sort:&#123;age:-1&#125;,</span><br><span class="line">	query:&#123;age:20&#125;, </span><br><span class="line">	limit:2</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="分片，分布式集群"><a href="#分片，分布式集群" class="headerlink" title="分片，分布式集群"></a>分片，分布式集群</h3><p><img src= "" data-lazy-src="D:\MyData\projects\lzo-docs-blog-2\static\img\2022-09-12_094526.jpg" alt="集群规划"></p>
<ol>
<li><p><strong>对比副本集：</strong>副本集类似备份，每个备份节点内容是一样的，不担心某个数据库挂了</p>
</li>
<li><p><strong>分布式集群：</strong>每个服务器只存能存下数据的一部分，满了，在开一个服务器，继续储存</p>
</li>
<li><p><strong>主要部分：</strong></p>
<ol>
<li><code>分片节点</code> - 普通mongod 进程，也可以是副本集，保存分片后的集合数据块</li>
<li><code>mongos路由节点</code> - 起到一个前端路由功能，供客户端进行接入，启动时从<code>配置节点</code>加载信息，当客户端连接到服务器时，会询问配置服务器，要到那个分片服务器上操作数据</li>
<li><code>配置节点</code> - 记录了<code>每个分片服务器</code>包含了<code>哪些数据</code>的信息，保存的只是数据的<code>分布表</code></li>
</ol>
</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">1、启动三个分片节点</span></span><br><span class="line">mongod --shardsvr --dbpath &quot;/root/mongos/data1/data/&quot; --port 1111</span><br><span class="line">mongod --shardsvr --dbpath &quot;/root/mongos/data2/data/&quot; --port 2222</span><br><span class="line">mongod --shardsvr --dbpath &quot;/root/mongos/data3/data/&quot; --port 3333</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">配置文件 有一个</span> </span><br><span class="line">sharding:</span><br><span class="line">	clusterRile:shardsvr</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">2、启动配置节点副本集</span></span><br><span class="line">mongod --configsvr --replSet rs_cfg --dbpath &quot;/root/mongos/config_data7/data/&quot; --port 7777</span><br><span class="line">mongod --configsvr --replSet rs_cfg --dbpath &quot;/root/mongos/config_data78data/&quot; --port 8888</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">副本集哪有的配置信息初始化</span></span><br><span class="line">mongo --port 7777 # 登录 7777 端口服务</span><br><span class="line">cfg = &#123;</span><br><span class="line">	_id:&quot;rs_cfg&quot;,</span><br><span class="line">	configsvr:true,</span><br><span class="line">	members:[</span><br><span class="line">		&#123;_id:0,host:&quot;127.0.0.1:7777&quot;&#125;,</span><br><span class="line">		&#123;_id:1,host:&quot;127.0.0.1:8888&quot;&#125;</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br><span class="line">rs.initiate(cfg)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">3、启动 mongos 路由节点 (前面的都是mongod服务) 都在mongos操作所有数据，不需要去哪些分片节点了</span></span><br><span class="line">mongos --configdb 副本集名/配置节点地址 --port 端口</span><br><span class="line">mongos --configdb rs_cfg/localhost:7777,localhost:8888 --port 9999</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">4、将分片节点信息添加到路由服务器中</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mongo 5.x新版 sh. 肯都有改db.runCommand()</span></span><br><span class="line">mongo --port 9999 # 进入mongos 服务</span><br><span class="line">sh.addShard(&quot;localhost:1111&quot;) # sh 表示分布式集群</span><br><span class="line">sh.addShard(&quot;localhost:2222&quot;)</span><br><span class="line">sh.addShard(&quot;localhost:3333&quot;)</span><br><span class="line">sh.status() # 查看集群状态</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">5、启动分片，</span> </span><br><span class="line">sh.enableSharding(&quot;test&quot;) # 将test作为分片数据库</span><br><span class="line">db.runCommand(&#123;enableSharding:&quot;test&quot;&#125;) </span><br><span class="line">sh.shardCollection(&quot;test.persons&quot;,&#123;name:1&#125;) # 对test persons集合提供分片支持，片键name,1 代表启用name为片键</span><br><span class="line">db.runCommand(&#123;shardCollection:&quot;test.persons&quot;,key:&#123;name:1&#125;&#125;)</span><br><span class="line">db.runCommand(&#123;shardCollection:&quot;test.persons&quot;,key:&#123;_id:&quot;hashed&quot;&#125;&#125;) # hash 散列平均分片到所有分片</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">片键(shard key)，通过片键决定数据存到哪个节点分片，片键必须是集合文档中存在的，片键太有规律肯能所有的会被分片到同一个分片</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mongos 不允许插入没有片键的文档</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">设置分片时在集合中选一个键，该键的值作为财富数据的依据</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">6、使用 进入mongos --port 9999 服务，操作与以前单个服务一致</span></span><br><span class="line"> for(var i=0;i&lt;1000000;i++)&#123;db.persons.insert(&#123;name:&quot;name&quot;+i,age:i&#125;)&#125; # 测试数据储存位置</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="mongoose"><a href="#mongoose" class="headerlink" title="mongoose"></a>mongoose</h3><p><a target="_blank" rel="noopener" href="http://www.mongoosejs.net/docs/index.html">官网</a></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install mongoose</span><br></pre></td></tr></table></figure>

<p>基本使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mongoose = <span class="built_in">require</span>(<span class="string">&quot;mongoose&quot;</span>);</span><br><span class="line"><span class="comment">//链接数据库</span></span><br><span class="line"><span class="comment">//地址:mongodb://主机/数据库名</span></span><br><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">&quot;mongodb://localhost/test1&quot;</span>, &#123;</span><br><span class="line">    <span class="attr">useNewUrlParser</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">useUnifiedTopology</span>: <span class="literal">true</span>,</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//数据库链接对象</span></span><br><span class="line"><span class="keyword">var</span> db = mongoose.<span class="property">connection</span>;</span><br><span class="line">db.<span class="title function_">on</span>(<span class="string">&quot;error&quot;</span>, <span class="variable language_">console</span>.<span class="property">error</span>.<span class="title function_">bind</span>(<span class="variable language_">console</span>, <span class="string">&quot;connection error:&quot;</span>));</span><br><span class="line">db.<span class="title function_">once</span>(<span class="string">&quot;open&quot;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;链接成功&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//Mongoose 里，一切都始于Schema。</span></span><br><span class="line"><span class="comment">//创建一个和集合相关的schema对象(类似表头)</span></span><br><span class="line"><span class="keyword">var</span> <span class="title class_">Schema</span> = mongoose.<span class="property">Schema</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> userSchema = <span class="keyword">new</span> <span class="title class_">Schema</span>(&#123;</span><br><span class="line">    <span class="attr">us</span>: &#123; <span class="attr">type</span>: <span class="title class_">String</span>, <span class="attr">required</span>: <span class="literal">true</span> &#125;, <span class="comment">//标题:&#123;类型:String,是否必须:true,默认:&#x27;123456&#x27;&#125;</span></span><br><span class="line">    <span class="attr">ps</span>: &#123; <span class="attr">type</span>: <span class="title class_">String</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">default</span>: <span class="string">&quot;123456&quot;</span> &#125;,</span><br><span class="line">    <span class="attr">age</span>: <span class="title class_">Number</span>, <span class="comment">//年龄:Number类型</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//将schema对象转化为数据模型</span></span><br><span class="line"><span class="keyword">var</span> <span class="title class_">User</span> = mongoose.<span class="title function_">model</span>(<span class="string">&quot;user&quot;</span>, userSchema);</span><br><span class="line"><span class="keyword">var</span> <span class="title class_">UserTest</span> = mongoose.<span class="title function_">model</span>(<span class="string">&quot;usertest&quot;</span>, userSchema);</span><br><span class="line"><span class="comment">//该数据对象与集合相连(&#x27;test1里的集合名&#x27;,schema对象)</span></span><br><span class="line"><span class="comment">//数据库中的集合名会自动以复数形式表示</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//操作数据库</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//API文档 -&gt; 模型(mongoose的增删改查) -&gt; 插入方法 Model.insertMany()</span></span><br><span class="line"><span class="title class_">User</span>.<span class="title function_">insertMany</span>(&#123; <span class="attr">us</span>: <span class="string">&quot;123&quot;</span>, <span class="attr">ps</span>: <span class="string">&quot;456&quot;</span>, <span class="attr">age</span>: <span class="number">12</span> &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;插入成功&quot;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;插入失败：&quot;</span> + err);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询</span></span><br><span class="line"><span class="title class_">User</span>.<span class="title function_">find</span>(&#123; <span class="attr">age</span>: <span class="number">12</span> &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;查询成功&quot;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;查询失败：&quot;</span> + err);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//删除</span></span><br><span class="line"><span class="title class_">User</span>.<span class="title function_">remove</span>(&#123; <span class="attr">age</span>: <span class="number">12</span> &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;删除成功&quot;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;删除失败：&quot;</span> + err);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修改</span></span><br><span class="line"><span class="comment">//Model.update(&#x27;更新条件&#x27;,&#x27;更新内容&#x27;,[options],[callback]);</span></span><br><span class="line"><span class="title class_">User</span>.<span class="title function_">update</span>(&#123; <span class="attr">age</span>: <span class="number">20</span> &#125;, &#123; <span class="attr">us</span>: <span class="string">&quot;new123&quot;</span> &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;更新成功&quot;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;更新失败：&quot;</span> + err);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="导入导出备份"><a href="#导入导出备份" class="headerlink" title="导入导出备份"></a>导入导出备份</h2><h3 id="备份（-mongodump-）"><a href="#备份（-mongodump-）" class="headerlink" title="备份（ mongodump ）"></a>备份（ mongodump ）</h3><blockquote>
<p>  .bson 方式输出，无法查看</p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mongodump -h dbhost -d dbname -c cname -o dbdirectory</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbhost 需要备份的主机</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbname 需要备份的数据库</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">cname 需要备份的集合 (备份整个数据库就不需要 -c 了)</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbdirectory 输出存放位置</span></span><br><span class="line">mongodump -h 127.0.0.1:27017 -d test -c table -o /root/mongosave/</span><br><span class="line">mongodump -h 127.0.0.1 --port 27017 -d test -c table -o /root/mongosave/</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--auth 开启的 mongo</span></span><br><span class="line">mongodump -h 127.0.0.1:27017 -u admin -p 123456 --authenticationDatabase admin -d test ...</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">备份成功后生成两文件 .json 试一下概要信息，.bson(json 的二进制格式) 保存真正的数据</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="恢复-mongorestore"><a href="#恢复-mongorestore" class="headerlink" title="恢复 ( mongorestore )"></a>恢复 ( mongorestore )</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mongorestore -h dbhost ----nsInclude=<span class="string">&quot;数据库名.集合名&quot;</span> --<span class="built_in">dir</span>=dbdirectory</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbhost 需要备份的主机</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbdirectory 需要恢复的数据库、或集合的位置</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--drop 删除集合中所有数据，完全恢复备份的数据，备份后添加的数据会被删</span></span><br><span class="line">mongorestore -h 127.0.0.1:27017 --nsInclude=&quot;test.table&quot; --dir=/root/mongosave</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">账号密码</span></span><br><span class="line">mongorestore -h 127.0.0.1:27017 -u admin -p 123456 --authenticationDatabase admin --nsInclude=&quot;test.table&quot; --dir=/root/mongosave</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">数据恢复，会将备份之后删除的添加回来，备份之后添加的默认不动</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="导出-（-mongoexport-）"><a href="#导出-（-mongoexport-）" class="headerlink" title="导出 （ mongoexport ）"></a>导出 （ mongoexport ）</h3><blockquote>
<p>  得到一份可以可以看的 json 数据，普通数据，任何地方都能导入</p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mongoexport -h dbhost -d dbname -c cname -o dbdirectory/xxxx.json</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbhost 需要导出的主机</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbname 需要导出的数据库</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">cname 需要导出的集合</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">dbdirectory 输出存放位置</span></span><br><span class="line">mongoexport  -h 127.0.0.1:27017  -d test -c table -o /root/mongoexport/xx2.json</span><br><span class="line">mongoexport  -h 127.0.0.1:27017  -u admin -p 123456 --authenticationDatabase admin -d test -c table -o /root/mongoexport/xx2.json</span><br></pre></td></tr></table></figure>

<h3 id="导入-mongoimport"><a href="#导入-mongoimport" class="headerlink" title="导入 ( mongoimport )"></a>导入 ( mongoimport )</h3><blockquote>
<p>  在原有数据追加数据(_id重复会导致无法导入，没_id会自动生成_id)，不存在的数据库或集合，导入会自动创建</p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mongoimport -h 127.0.0.1:27017 -d test2 -c tab2 ./mongoexport/xx2.json</span><br><span class="line">mongoimport -h 127.0.0.1:27017 -u admin -p 123456 --authenticationDatabase admin -d test2 -c tab2 ./mongoexport/xx2.json</span><br></pre></td></tr></table></figure>











<ul>
<li>数据库相关工具<ul>
<li>导入<code>mongoimport</code><ul>
<li><code>-h</code> : 指明数据库宿主机的IP</li>
<li><code>-u</code> : 指明数据库的用户名</li>
<li><code>-p</code> : 指明数据库的密码</li>
<li><code>-d</code> : 指明数据库的名字</li>
<li><code>-c</code> : 指明collection的名字</li>
<li><code>-f</code> : 指明要导出那些列</li>
<li><code>-o</code> : 指明到要导出的文件名</li>
<li><code>-q</code> : 指明导出数据的过滤条件</li>
<li></li>
<li><code>mongoexport -d pro-node-lagou -c menus -o D:\lzo-project\lzo-everyday\mongodb-export\menus.dat</code></li>
<li><code>mongoexport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -c 表名 -f 字段1，字段2 -q‘&#123;条件导出&#125;’ </code>–csv -o 文件名</li>
</ul>
</li>
<li>导出<code>mongoexport</code><ul>
<li><code>-h</code> : 指明数据库宿主机的IP</li>
<li><code>-u</code> : 指明数据库的用户名</li>
<li><code>-p</code> : 指明数据库的密码</li>
<li><code>-d</code> : 指明数据库的名字</li>
<li><code>-c</code> : 指明collection的名字</li>
<li><code>-f</code> : 指明要导入那些列</li>
<li><code>mongoimport -d pro-node-lagou -c menus menus.dat</code></li>
</ul>
</li>
<li>恢复<code>mongorestore</code><ul>
<li><code>mongorestore D:\lzo-project\lzo-everyday\mongodb-export</code></li>
</ul>
</li>
<li><code>mongofiles</code>保存大文件</li>
<li><code>mongostat</code>是mongodb自带的状态检测工具</li>
<li><code>mongotop</code>用来跟踪MongoDB的实例</li>
</ul>
</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">lzoxun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/07/22/server/node/server-mongodb/">http://example.com/2023/07/22/server/node/server-mongodb/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">学习笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/07/22/server/node/server-issues/" title="问题"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">问题</div></div></a></div><div class="next-post pull-right"><a href="/2023/07/22/server/go/go-bash/" title="go"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">go</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">lzoxun</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liaozhongxun"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liaozhongxun" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:869664233@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的文档</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%8B%E8%BD%BD%E5%AE%89%E8%A3%85-M%E5%B1%82"><span class="toc-number">1.</span> <span class="toc-text">下载安装(M层)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">1.1.</span> <span class="toc-text">安装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-number">1.2.</span> <span class="toc-text">连接数据库</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9B%BE%E5%BD%A2%E5%B7%A5%E5%85%B7%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.2.1.</span> <span class="toc-text">图形工具连接</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B7%A5%E5%85%B7%E8%BF%9E%E6%8E%A5%E8%BF%9C%E7%A8%8B"><span class="toc-number">1.2.2.</span> <span class="toc-text">工具连接远程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4%E8%A1%8C%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.2.3.</span> <span class="toc-text">命令行连接</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#mongoose-%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.2.4.</span> <span class="toc-text">mongoose 连接</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%89%E5%85%A8"><span class="toc-number">2.</span> <span class="toc-text">安全</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8%E6%88%B7%E7%AE%A1%E7%90%86%E6%9D%83%E9%99%90"><span class="toc-number">2.1.</span> <span class="toc-text">用户管理权限</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%AF%E6%9C%AC%E9%9B%86-replication-%E5%A4%8D%E5%88%B6"><span class="toc-number">2.2.</span> <span class="toc-text">副本集(replication) 复制</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%89%AF%E6%9C%AC%E9%9B%86"><span class="toc-number">2.2.1.</span> <span class="toc-text">多服务器副本集</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MongoDB-%E4%BD%BF%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">MongoDB 使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-number">3.1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%93%8D%E4%BD%9C%E6%8C%87%E4%BB%A4"><span class="toc-number">3.2.</span> <span class="toc-text">操作指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5"><span class="toc-number">3.3.</span> <span class="toc-text">数据库增删改查</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B4%A2%E5%BC%95"><span class="toc-number">3.4.</span> <span class="toc-text">索引</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E7%BB%84-group"><span class="toc-number">3.5.</span> <span class="toc-text">分组(group)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%81%9A%E5%90%88-aggragate"><span class="toc-number">3.6.</span> <span class="toc-text">聚合(aggragate)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MapReduce"><span class="toc-number">3.7.</span> <span class="toc-text">MapReduce</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E7%89%87%EF%BC%8C%E5%88%86%E5%B8%83%E5%BC%8F%E9%9B%86%E7%BE%A4"><span class="toc-number">3.8.</span> <span class="toc-text">分片，分布式集群</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#mongoose"><span class="toc-number">3.9.</span> <span class="toc-text">mongoose</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%BC%E5%85%A5%E5%AF%BC%E5%87%BA%E5%A4%87%E4%BB%BD"><span class="toc-number">4.</span> <span class="toc-text">导入导出备份</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%87%E4%BB%BD%EF%BC%88-mongodump-%EF%BC%89"><span class="toc-number">4.1.</span> <span class="toc-text">备份（ mongodump ）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%81%A2%E5%A4%8D-mongorestore"><span class="toc-number">4.2.</span> <span class="toc-text">恢复 ( mongorestore )</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%87%BA-%EF%BC%88-mongoexport-%EF%BC%89"><span class="toc-number">4.3.</span> <span class="toc-text">导出 （ mongoexport ）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%85%A5-mongoimport"><span class="toc-number">4.4.</span> <span class="toc-text">导入 ( mongoimport )</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-11/" title="win 11 set">win 11 set</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-gitbash/" title="git bash">git bash</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-wsl/" title="wsl">wsl</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-main/" title="window">window</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/web/%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98/" title="兼容问题">兼容问题</a><time datetime="2023-07-22T07:14:09.699Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By lzoxun</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":100,"height":200,"right":300},"mobile":{"show":true}});</script></body></html>